package com.example.jack.community.view.dynamic;


import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jack.community.R;
import com.example.jack.community.view.dynamic.dynamic_bean.Md5;
import com.example.jack.community.view.dynamic.dynamic_bean.RecyclerViewAdapter;
import com.example.jack.community.view.dynamic.dynamic_bean.activityData;
import com.example.jack.community.view.dynamic.dynamic_data.DateUtils;
import com.example.jack.community.view.dynamic.dynamic_data.Gson1;
import com.example.jack.community.view.dynamic.dynamic_data.StateJudgment;
import com.example.jack.community.view.dynamic.dynamic_data.activityDataGson;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;


/**
 * A simple {@link Fragment} subclass.
 */
public class DynamicFragment extends Fragment implements View.OnClickListener {

    public static Fragment context;

    private ViewPager vp_navigation;
    private List<View> mViews = new ArrayList<View>();
    private ImageView dynamic_imageView1, dynamic_imageView2;
    private TextView dynamic_textView1, dynamic_textView2;
    private LinearLayout dynamic_LinearLayout1, dynamic_LinearLayout2, dynamic_search;
    private View activity_1, activity_2;

    private List<activityData> dataList = new ArrayList<>();
    private List<activityData> dataList1 = new ArrayList<>();

    private XRecyclerView XRecyclerView1, XRecyclerView2;
    private RecyclerViewAdapter mRecyclerViewAdapter1, mRecyclerViewAdapter2;

    private static final String TAG = "RegisterPresenterlmps";

    Handler handler = new Handler();
    int abb, add = 1;
    String num1 = "1";
    activityDataGson activitydataGson;
    Gson gson2 = new Gson();
    String num, token = "2e2ca66eb61de524d88da7785df7d7d157102dab0353bac710002311c45b3abc";//加密密匙，常用密匙

    public DynamicFragment() {
        // Required empty public constructor
    }

    public static DynamicFragment newInstance(String s1) {
        DynamicFragment fragment = new DynamicFragment();
        Bundle args = new Bundle();
        args.putString("agrs1", s1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        //fragment里绑定控件
        View myFragment = inflater.inflate(R.layout.fragment_dynamic, container, false);
        vp_navigation = (ViewPager) myFragment.findViewById(R.id.vp_navigation);
        dynamic_imageView1 = (ImageView) myFragment.findViewById(R.id.dynamic_imageView1);
        dynamic_imageView2 = (ImageView) myFragment.findViewById(R.id.dynamic_imageView2);
        dynamic_LinearLayout1 = (LinearLayout) myFragment.findViewById(R.id.dynamic_LinearLayout1);
        dynamic_LinearLayout2 = (LinearLayout) myFragment.findViewById(R.id.dynamic_LinearLayout2);
        dynamic_search = (LinearLayout) myFragment.findViewById(R.id.dynamic_search);
        dynamic_textView1 = (TextView) myFragment.findViewById(R.id.dynamic_textView1);
        dynamic_textView2 = (TextView) myFragment.findViewById(R.id.dynamic_textView2);

        initViews();//绑定Viewpager
        abb = 1;
        initPicture();//滑动监听事件
        return myFragment;
    }

    private void initPicture() {
        dynamic_LinearLayout1.setOnClickListener(this);
        dynamic_LinearLayout2.setOnClickListener(this);
        dynamic_search.setOnClickListener(this);

        //监听滑动事件
        vp_navigation.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            //滑动改变图标
            @Override
            public void onPageSelected(int arg0) {
                int currentItem = vp_navigation.getCurrentItem();
                resetImg();
                switch (currentItem) {
                    case 0:
                        abb = 1;
                        dynamic_imageView1.setImageResource(R.drawable.underline);
                        dynamic_textView1.setTextColor(Color.parseColor("#e6c42c"));
                        break;
                    case 1:
                        abb = 0;
                        //进入界面重新加载数据
                        if (add == 0) {
                            XRecyclerView2.refresh();
                            add = 3;
                        }
                        dynamic_imageView2.setImageResource(R.drawable.underline);
                        dynamic_textView2.setTextColor(Color.parseColor("#e6c42c"));
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    //图片切换成暗色的，没被点击到或者移动到
    private void resetImg() {
        dynamic_imageView1.setImageResource(R.mipmap.ic_back);
        dynamic_imageView2.setImageResource(R.mipmap.ic_back);
        dynamic_textView1.setTextColor(Color.parseColor("#ffffff"));
        dynamic_textView2.setTextColor(Color.parseColor("#ffffff"));
    }

    private void initViews() {
        LayoutInflater mInflater = LayoutInflater.from(getActivity());
        activity_1 = mInflater.inflate(R.layout.viewpager_underway, null);
        activity_2 = mInflater.inflate(R.layout.viewpager_review, null);
        //通过判断解决界面多次出现加载问题
        if (mViews.size() < 1) {
            mViews.add(activity_1);
            mViews.add(activity_2);
            //导入recyclerView数据
//            initData();
//            initData1();
        }

        //绑定控件recyclerView，控件绑定一定要在相对应activity下绑定
        XRecyclerView1 = (XRecyclerView) activity_1.findViewById(R.id.XRecyclerView1);
        LinearLayoutManager layoutManager1 = new LinearLayoutManager(getActivity());
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        XRecyclerView1.setLayoutManager(layoutManager1);
        mRecyclerViewAdapter1 = new RecyclerViewAdapter(getActivity(), dataList);
        XRecyclerView1.setAdapter(mRecyclerViewAdapter1);
        XRecyclerView1.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        XRecyclerView1.setLoadingMoreProgressStyle(ProgressStyle.TriangleSkewSpin);
        XRecyclerView1.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override//下拉刷新数据
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        dataList.clear();
                        iniIntent();
                    }

                }, 1000);
            }

            @Override//上拉加载数据
            public void onLoadMore() {
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        iniIntent();
                    }
                }, 1000);
            }
        });
        //进入界面重新加载数据
        if (add == 1) {
            XRecyclerView1.refresh();
            add = 0;
        }


        XRecyclerView2 = (XRecyclerView) activity_2.findViewById(R.id.XRecyclerView2);
        LinearLayoutManager layoutManager2 = new LinearLayoutManager(getActivity());
        layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        XRecyclerView2.setLayoutManager(layoutManager2);
        mRecyclerViewAdapter2 = new RecyclerViewAdapter(getActivity(), dataList1);
        XRecyclerView2.setAdapter(mRecyclerViewAdapter2);
        XRecyclerView2.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        XRecyclerView2.setLoadingMoreProgressStyle(ProgressStyle.TriangleSkewSpin);
        XRecyclerView2.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override//下拉刷新数据
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    public void run() {

                        dataList1.clear();
                        iniIntent2();
                    }

                }, 1000);
            }

            @Override//上拉加载数据
            public void onLoadMore() {
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        iniIntent2();
                    }
                }, 1000);
            }
        });

        //正在进行活动的点击事件
        mRecyclerViewAdapter1.setOnItemClickListener(new RecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity(), DynamicActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                intent.putExtra("number", dataList.get(position - 1).getActivityid());
                //给intent添加额外数据，key为“number”,key值为该界面的JSON数组
                startActivity(intent);
            }
        });

        //已经结束活动的点击事件
        mRecyclerViewAdapter2.setOnItemClickListener(new RecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity(), DynamicActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                intent.putExtra("number", dataList1.get(position - 1).getActivityid());
                //给intent添加额外数据，key为“number”,key值为该界面的JSON数组
                startActivity(intent);
            }
        });


        vp_navigation.setAdapter(mAdapter);
    }


    //点击事件
    public void onClick(View v) {
        resetImg();
        switch (v.getId()) {
            case R.id.dynamic_LinearLayout1:
                vp_navigation.setCurrentItem(0);
                abb = 1;
                dynamic_imageView1.setImageResource(R.drawable.underline);
                dynamic_textView1.setTextColor(Color.parseColor("#e6c42c"));
                break;
            case R.id.dynamic_LinearLayout2:
                abb = 0;//进入界面重新加载数据
                vp_navigation.setCurrentItem(1);
                dynamic_imageView2.setImageResource(R.drawable.underline);
                dynamic_textView2.setTextColor(Color.parseColor("#e6c42c"));
                break;
            case R.id.dynamic_search:
                if (abb == 1) {
                    dynamic_imageView1.setImageResource(R.drawable.underline);
                    dynamic_textView1.setTextColor(Color.parseColor("#e6c42c"));
                } else if (abb == 0) {
                    dynamic_imageView2.setImageResource(R.drawable.underline);
                    dynamic_textView2.setTextColor(Color.parseColor("#e6c42c"));
                }
                Intent intent1 = new Intent(getActivity(), DynamicSearch.class);
                intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        intent1.putExtra("KeyConvert", KeyConvert);//给intent添加额外数据，key为“str”,key值为key3
                startActivity(intent1);
        }
    }

    //ViewPager PagerAdapter适配器
    PagerAdapter mAdapter = new PagerAdapter() {

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mViews.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = mViews.get(position);
            container.addView(view);
            return view;
        }

        @Override
        public int getCount() {
            return mViews.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }
    };


    //网络请求数据get数据
    private void iniIntent2() {
        String url;
        url = "http://192.168.1.11/activitiessimple/";
        OkHttpUtils
                .get()
                .url(url)
                .id(100)
                .build()
                .execute(new MyStringCallback2());
    }


    //okhttp_utils的get请求封装好的方法
    public class MyStringCallback2 extends StringCallback {

        @Override//错误报备
        public void onError(Call call, Exception e, int id) {
            e.printStackTrace();
            Toast.makeText(getActivity(), "请确认网络是否正常开启", Toast.LENGTH_SHORT).show();
            XRecyclerView2.refreshComplete();
        }

        @Override//回调
        public void onResponse(String response, int id) {
            String str = response;//str为get获取的全部数据
            Gson gson = new Gson();
            Gson1 activityMd5numGson = gson.fromJson(str, Gson1.class);//activityMd5numGson为Gson解析后的数据
            Md5 activityMd5numMd5 = new Md5();
            String md5num = activityMd5numMd5.md5(activityMd5numGson.getData());//md5num为加密后的Data数据
            num = md5num.substring(20, 30);//num为md5num的20和30位

            //Post数据
            iniIntent3();
        }
    }

    //Post数据第二次
    private void iniIntent3() {
        String url;
        url = "http://192.168.1.11/activitiessimple/";
        OkHttpUtils
                .post()
                .url(url)
                .addParams("getPagesNum", num1)//带上参数访问
                .addParams("passcode", num)//带上参数访问
                .addParams("token", token)//带上参数访问
                .id(100)
                .build()
                .execute(new MyStringCallback3());
    }

    //okhttp_utils的post请求封装好的方法
    public class MyStringCallback3 extends StringCallback {

        @Override//错误报备
        public void onError(Call call, Exception e, int id) {
            e.printStackTrace();
//            tv_show.setText( "onError:" + e.getMessage() );
        }

        @Override//回调
        public void onResponse(String response, int id) {
            String str1 = response;//str1为post获取的全部数据
            Gson gson = new Gson();
            activitydataGson = gson.fromJson(str1, activityDataGson.class);//activityData为Gson解析后的数据

            initData1();

            mRecyclerViewAdapter2.notifyDataSetChanged();
            XRecyclerView2.refreshComplete();
        }
    }

    //网络请求数据get数据
    private void iniIntent() {
        String url;
        url = "http://192.168.1.11/activitiessimple/";
        OkHttpUtils
                .get()
                .url(url)
                .id(100)
                .build()
                .execute(new MyStringCallback());
    }

    //okhttp_utils的get请求封装好的方法
    public class MyStringCallback extends StringCallback {

        @Override//错误报备
        public void onError(Call call, Exception e, int id) {
            e.printStackTrace();
            Toast.makeText(getActivity(), "请确认网络是否正常开启", Toast.LENGTH_SHORT).show();
            XRecyclerView1.refreshComplete();
        }

        @Override//回调
        public void onResponse(String response, int id) {
            String str = response;//str为get获取的全部数据
            Gson gson = new Gson();
            Gson1 activityMd5numGson = gson.fromJson(str, Gson1.class);//activityMd5numGson为Gson解析后的数据
            Md5 activityMd5numMd5 = new Md5();
            String md5num = activityMd5numMd5.md5(activityMd5numGson.getData());//md5num为加密后的Data数据
            num = md5num.substring(20, 30);//num为md5num的20和30位


            //Post数据
            iniIntent1();
        }

        //Post数据第二次
        private void iniIntent1() {
            String url;
            url = "http://192.168.1.11/activitiessimple/";
            OkHttpUtils
                    .post()
                    .url(url)
                    .addParams("getPagesNum", num1)//带上参数访问
                    .addParams("passcode", num)//带上参数访问
                    .addParams("token", token)//带上参数访问
                    .id(100)
                    .build()
                    .execute(new MyStringCallback1());
        }

        //okhttp_utils的post请求封装好的方法
        public class MyStringCallback1 extends StringCallback {

            @Override//错误报备
            public void onError(Call call, Exception e, int id) {
                e.printStackTrace();
//            tv_show.setText( "onError:" + e.getMessage() );
            }

            @Override//回调
            public void onResponse(String response, int id) {
                String str1 = response;//str1为post获取的全部数据
                // 用到知识点Gson 解析List列表
                // 注意格式要为JsonArray
                Log.e("312312",str1);
                Gson gson = new Gson();
                activitydataGson = gson.fromJson(str1, activityDataGson.class);//activityData为Gson解析后的数据
                initData();
                Log.e("tensa", String.valueOf(activitydataGson.getData().get(0).getStartActivitiesTime()));
                Log.e("tensa", String.valueOf(activitydataGson.getData().get(0).getEndActivitiesTime()));
                Log.e("tensa", DateUtils.getTimeConversionDate(activitydataGson.getData().get(0).getStartActivitiesTime(),
                        activitydataGson.getData().get(0).getEndActivitiesTime()));

                mRecyclerViewAdapter1.notifyDataSetChanged();
                XRecyclerView1.refreshComplete();
            }
        }
    }

    //加载数据--正在进行界面
    private void initData() {
        for (int i = 0; i < activitydataGson.getData().size(); i++) {
            activityData num = new activityData(
                    StateJudgment.PictureRequest(activitydataGson.getData().get(i).getPoster()),
                    StateJudgment.PictureRequest(activitydataGson.getData().get(i).getCommunityLogo()),
                    activitydataGson.getData().get(i).getCommunityName().intern(),
                    StateJudgment.typeJudgment(activitydataGson.getData().get(i).getCategory()),
                    DateUtils.getDistanceTime(activitydataGson.getData().get(i).getActivitiesReleaseTimeStamp()),
                    activitydataGson.getData().get(i).getActivitiesStatus(),
                    DateUtils.getTimeConversionDate(activitydataGson.getData().get(i).getStartActivitiesTime(),
                            activitydataGson.getData().get(i).getEndActivitiesTime()),
                    gson2.toJson(activitydataGson.getData().get(i)));
            dataList.add(num);
        }
    }

    //加载数据--往期回顾界面
    private void initData1() {
        for (int i = 0; i < activitydataGson.getData().size(); i++) {
            activityData num = new activityData(
                    StateJudgment.PictureRequest(activitydataGson.getData().get(i).getPoster()),
                    StateJudgment.PictureRequest(activitydataGson.getData().get(i).getCommunityLogo()),
                    activitydataGson.getData().get(i).getCommunityName().intern(),
                    StateJudgment.typeJudgment(activitydataGson.getData().get(i).getCategory()),
                    DateUtils.getDistanceTime(activitydataGson.getData().get(i).getActivitiesReleaseTimeStamp()),
                    activitydataGson.getData().get(i).getActivitiesStatus(),
                    DateUtils.getTimeConversionDate(activitydataGson.getData().get(i).getStartActivitiesTime(),
                            activitydataGson.getData().get(i).getEndActivitiesTime()),
                    gson2.toJson(activitydataGson.getData().get(i)));
            dataList1.add(num);
        }
    }
}
